const { body, check } = require('express-validator')
const validate = require('../middleware/validator')
const { User } = require('../model')
const Error = require('../config/error-code')
const secret = require('../utils/secret')

const pwdReg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,16}$/;

// 注册验证
exports.register = validate([
    // 1. 配置验证规则，使用withMessage定制错误消息。
    // .bail()为：如果验证失败，后面代码不继续执行，否则继续执行。
    // .custom为自定义验证方法
    body('email')
        .trim().notEmpty().withMessage(Error['XP016']).bail()
        .isEmail().withMessage(Error['XP017']).bail()
        .custom(
            async email => {
                const user = await User.findOne({ email })
                if (user) {
                    return Promise.reject(Error['XP018'])
                }
            }
        ).bail(),
    body('registerPassword').notEmpty().withMessage(Error['XP011']).bail()
        .custom(async (registerPassword, { req }) => {
            try {
                let decryptPassword = secret.Decrypt(registerPassword)
                if (!pwdReg.test(decryptPassword)) {
                    return Promise.reject(Error['XP026'])
                }
                if (decryptPassword.length > 16 || decryptPassword.length < 6) {
                    return Promise.reject(Error['XP027'])
                }
            } catch(err) {
                return Promise.reject(Error['XP031'])
            }
        }).bail(),
    body('nickname')
        .trim().notEmpty().withMessage(Error['XP014']).bail()
        .isLength({ min:2, max:8 }).withMessage(Error['XP028']).bail(),
    body('sex').notEmpty().withMessage(Error['XP019'])
])

exports.login = [
    validate([
        body('username').trim().notEmpty().withMessage(Error['XP010']).bail()
        .custom(async (username, { req }) => {
            const user = await User.findOne({ username })
                .select('username password nickname email avatar sex isEnable createdAt updatedAt')
            if (!user) {
                return Promise.reject(Error['XP012'])
            }
            if (!user.isEnable) {
                return Promise.reject(Error['XP015'])
            }
            req.user = user
        })
    ]),
    validate([
        body('password').notEmpty().withMessage(Error['XP011']).bail()
        .custom(async (password, { req }) => {
            if (password !== req.user.password) {
                return Promise.reject(Error['XP013'])
            }
        })
    ])
]

exports.forgetUser = validate([
    body('email')
        .trim().notEmpty().withMessage(Error['XP016']).bail()
        .isEmail().withMessage(Error['XP017']).bail()
        .custom(
            async (email, { req }) => {
                const user = await User.findOne({ email })
                if (!user) {
                    return Promise.reject(Error['XP051'])
                }
                req.user = user
            }
        )
])



